#!/bin/bash

# Credit: https://github.com/DataDog/datadog-agent/blob/7.32.4/Dockerfiles/manifests/generate.sh

set -euo pipefail
IFS=$'\n\t'

if sed --version 2>/dev/null | grep -q "GNU sed"; then
    SED="sed"
elif gsed --version 2>/dev/null | grep -q "GNU sed"; then
    SED="gsed"
fi

cd "$(dirname "${BASH_SOURCE[0]}")/.."

helm repo add vector https://helm.vector.dev
helm repo update

TMPDIR=$(mktemp -d)
trap 'rm -r $TMPDIR' EXIT

cat > "$TMPDIR/values-vector-agent.yaml" <<EOF
role: Agent
service:
  enabled: false
EOF

cat > "$TMPDIR/values-vector-aggregator.yaml" <<EOF
EOF

cat > "$TMPDIR/values-vector-stateless-aggregator.yaml" <<EOF
role: Stateless-Aggregator
EOF

CLEANUP_INSTRUCTIONS='del(.metadata.labels."helm.sh/chart") | del(.metadata.labels."app.kubernetes.io/managed-by") | del(.metadata.annotations.checksum/*) | del(.spec.template.metadata.annotations.checksum/*)'

for values in "$TMPDIR"/values-*.yaml; do
    type=${values##*values-}
    type=${type%.yaml}

    rm -rf "${type:?}"
    mkdir "${type:?}"

    helm template --namespace default vector vector/vector --values "$values" --output-dir "$TMPDIR/generated_$type"
    for file in "$TMPDIR/generated_$type"/vector/templates/*.yaml; do
        # Skip files containing only comments
        if [[ "$(yq eval '. | length' "$file")" == 0 ]]; then
            rm "$file"
            continue
        fi
        # We want this to output without expansion
        # shellcheck disable=SC2016
        ${SED:-sed} -E -i 's/^# Source: (.*)/# This file has been generated by `helm template vector vector\/vector` from \1. Please re-run `make generate-kubernetes-manifests` rather than modifying this file manually./' "$file"
        yq eval "$CLEANUP_INSTRUCTIONS" "$file" > "distribution/kubernetes/$type/$(basename "$file")"
    done

    cat > "distribution/kubernetes/$type/README.md" <<EOF
The kubernetes manifests found in this directory have been automatically generated
from the [helm chart \`vector/vector\`](https://github.com/vectordotdev/helm-charts/tree/master/charts/vector)
version $(helm show chart vector/vector | yq e '.version' -) with the following \`values.yaml\`:

\`\`\`yaml
$(<"$values")
\`\`\`
EOF
    rm -rf "${type:?}"
done
